/*
 * @Author       : 刘洋 liuy5335@163.com
 * @Date         : 2024-05-15 14:54:55
 * @LastEditors: zhaozhen zack960116@163.com
 * @LastEditTime: 2024-08-21 10:10:43
 * @FilePath     : \zhly-vform\src\utils\request.ts
 * @Description  : 接口请求封装
 *
 * Copyright (c) 2024 by zhlx - liuy5335@163.com, All Rights Reserved.
 */
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'

// 创建一个axios实例
const service = axios.create({
  baseURL: '/api', // 设置你的API基础URL
  timeout: 10000, // 设置请求超时时间
})

// 添加请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 从localStorage或sessionStorage中获取token
    const token = sessionStorage.getItem('token') || sessionStorage.getItem('userStore')['token']
    const tenantId = sessionStorage.getItem('tenantId') || sessionStorage.getItem('userStore')['tenantId']

    // 在请求头中添加token 租户id
    config.headers = Object.assign(config.headers, {
      Authorization: token
        ? `Bearer ${token}`
        : 'Bearer IFtdSZQt_xo4o7TQCMT6_ruKzY54sPfhN0fgVvlR5iu8kJjRkT6FZKeSf8wfioTU2vfsJ7y67atR7MPNqIwWQCerYEnIuHCYxX7TpplgsnfZIhj4dOFRuQRvuXtG2fnY',
      'TENANT-ID': tenantId ? tenantId : '1776583155000602626',
    })
    return config
  },
  (error) => {
    // 处理请求错误
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 处理响应数据
    return response.data
  },
  (error) => {
    // 处理响应错误
    console.error(error) // for debug
    return Promise.reject(error)
  }
)
export default window && window.vformService ? window.vformService : service;
